import {
  Bubble,
  Sender,
  Prompts,
  XStream,
  useXAgent,
  useXChat
} from "@ant-design/x"
import {
  UserOutlined,
  UploadOutlined,
  BulbOutlined,
  InfoCircleOutlined,
  WarningOutlined,
  RocketOutlined,
  CheckCircleOutlined,
  CoffeeOutlined,
  SmileOutlined,
  FireOutlined
} from "@ant-design/icons"
import { useState, useRef } from "react"
import { Button, message as antMessage, Upload, Select } from "antd"
import { useLayoutEffect } from "react"
import { useNavigate } from "react-router-dom"

import { getCompanyList, sseWithPost } from "../../request/api"
import useMount from "../../hooks/useMount"

const roles = {
  ai: {
    placement: "start",
    avatar: { icon: <UserOutlined />, style: { background: "#fde3cf" } },
    typing: { step: 5, interval: 20 },
    style: {
      maxWidth: 600
    }
  },
  local: {
    placement: "end",
    avatar: { icon: <UserOutlined />, style: { background: "#87d068" } }
  }
}

// eslint-disable-next-line no-unused-vars
const promptItems = [
  {
    key: "1",
    icon: <BulbOutlined style={{ color: "#FFD700" }} />,
    description: "Got any sparks for a new project?"
  },
  {
    key: "2",
    icon: <InfoCircleOutlined style={{ color: "#1890FF" }} />,
    description: "Help me understand the background of this topic."
  },
  {
    key: "3",
    icon: <WarningOutlined style={{ color: "#FF4D4F" }} />,
    description: "How to solve common issues? Share some tips!"
  },
  {
    key: "4",
    icon: <RocketOutlined style={{ color: "#722ED1" }} />,
    description: "How can I work faster and better?"
  },
  {
    key: "5",
    icon: <CheckCircleOutlined style={{ color: "#52C41A" }} />,
    description: "What are some tricks for getting tasks done?"
  }
  // {
  //   key: '6',
  //   icon: <CoffeeOutlined style={{ color: '#964B00' }} />,
  //   description: 'How to rest effectively after long hours of work?',
  // },
  // {
  //   key: '7',
  //   icon: <SmileOutlined style={{ color: '#FAAD14' }} />,
  //   description: 'What are the secrets to maintaining a positive mindset?',
  // },
  // {
  //   key: '8',
  //   icon: <FireOutlined style={{ color: '#FF4D4F' }} />,
  //   description: 'How to stay calm under immense pressure?',
  // },
]

const uploadProps = {
  name: "file",
  action: "https://660d2bd96ddfa2943b33731c.mockapi.io/api/upload",
  headers: {
    authorization: "authorization-text"
  },
  onChange(info) {
    if (info.file.status !== "uploading") {
      console.log(info.file, info.fileList)
    }
    if (info.file.status === "done") {
      antMessage.success(`${info.file.name} file uploaded successfully`)
    } else if (info.file.status === "error") {
      antMessage.error(`${info.file.name} file upload failed.`)
    }
  }
}

// const companyList = [
//         "华中科技",
//         "国网京山疗养中心",
//         "国网十堰供电公司",
//         "国网咸宁供电公司",
//         "国网孝感供电公司",
//         "国网宜昌供电公司",
//         "国网恩施供电公司",
//         "国网武汉供电公司",
//         "国网湖北中超公司",
//         "国网湖北信通公司",
//         "国网湖北实业公司",
//         "国网湖北技培中心",
//         "国网湖北物资公司",
//         "国网湖北电动汽车",
//         "国网湖北电科院",
//         "国网湖北直流公司",
//         "国网湖北管培中心",
//         "国网湖北综合能源",
//         "国网湖北超高压公司",
//         "国网湖北送变电公司",
//         "国网湖北黄龙滩电厂",
//         "国网神农架供电公司",
//         "国网荆州供电公司",
//         "国网荆门供电公司",
//         "国网襄阳供电公司",
//         "国网鄂州供电公司",
//         "国网随州供电公司",
//         "国网黄冈供电公司",
//         "国网黄石供电公司",
//         "正源集团",
//         "武汉鄂电会务服务有限公司",
//         "计量中心"
//     ]

const Message = ({ title }) => {
  const navigate = useNavigate()
  const [value, setValue] = useState("")

  const headerRef = useRef(null)
  const footerRef = useRef(null)
  const [contentHeight, setContentHeight] = useState(300)

  const [companyName, setCompanyName] = useState("")
  const [companyName1, setCompanyName1] = useState("")
  // eslint-disable-next-line no-unused-vars
  const [messageApi, contextHolder] = antMessage.useMessage()

  const [companyList, setCompanyList] = useState([])

  let didInit = false
  useMount(async () => {
    if (!didInit) {
      didInit = true
      const res = await getCompanyList()
      if (res && Array.isArray(res.data)) {
        setCompanyList(res.data)
      }
    }
  }, [])

  useLayoutEffect(() => {
    function updateContentHeight() {
      if (headerRef.current && footerRef.current) {
        const headerHeight = headerRef.current.offsetHeight
        const footerHeight = footerRef.current.offsetHeight
        const windowHeight = window.innerHeight

        // 计算中间内容区域的高度
        const calculatedHeight = windowHeight - headerHeight - footerHeight

        console.log(windowHeight, headerHeight, footerHeight, calculatedHeight)

        // 确保高度不为负值
        setContentHeight(Math.max(calculatedHeight, 0))
      }
    }

    updateContentHeight()

    window.addEventListener("resize", updateContentHeight)
    return () => {
      window.removeEventListener("resize", updateContentHeight)
    }
  }, [])

  const extractContent = (text) => {
    if (!text) return
    const regex = /(国网.+?公司)/g
    const matches = text.match(regex)
    if (matches.length > 0) {
      setCompanyName(matches[0])
      console.log(matches[0])
    }
  }

  // const handleClickReport = () => {
  //   if (!companyName) {
  //     messageApi.open({
  //       type: "warning",
  //       content: "没有选中公司"
  //     })
  //     return
  //   }
  //   const encodedName = encodeURIComponent(companyName)
  //   navigate(`/report?companyName=${encodedName}`)
  // }

  const handleClickAudit = () => {
    const encodedName = encodeURIComponent(companyName)
    navigate(`/assistant-decision?companyName=${encodedName}`)
  }
  // 专业画像
  const handleClickMajor = () => {
    const encodedName = encodeURIComponent(companyName)
    navigate(`/professional-portrait?companyName=${encodedName}`)
  }

  // 画像对比
  const handleClickCompare = () => {
    const encodedName1 = encodeURIComponent(companyName)
    const encodedName2 = encodeURIComponent(companyName1)
    navigate(`/professional-compare?compare1=${encodedName1}&compare2=${encodedName2}`)
  }

  // Agent for request
  const [agent] = useXAgent({
    request: async ({ message }, { onSuccess, onUpdate }) => {
      try {
        let text = ""
        await sseWithPost(message, (res) => {
          if (res.type === "message") {
            text += res.data
            onUpdate(text)
          }
        })
        onSuccess([text])
      } catch (error) {
        console.log(error)
        onSuccess([error.message])
      }
    }
  })

  // Chat messages
  const { onRequest, messages } = useXChat({
    requestPlaceholder: "正在思考...",
    agent
  })

  const listRef = useRef(null)

  const handleChangeCompany = (value) => {
    setCompanyName(value)
  }
  const handleChangeCompany1 = (value) => {
    setCompanyName1(value)
  }

  return (
    <div className="flex-1 flex flex-col overflow-hidden">
      {contextHolder}
      <header
        ref={headerRef}
        className="h-[76px] shrink-0 flex px-6 n items-center text-xl border-b border-gray-100"
      >
        <span className="mr-auto">{title}</span>
        <Select
          size="large"
          value={companyName}
          style={{ width: 200 }}
          onChange={handleChangeCompany}
          options={companyList.map((item) => ({
            value: item,
            label: item
          }))}
        />
        {/* <Button
          type="primary"
          className="mx-4"
          size="large"
          onClick={handleClickReport}
        >
          {companyName || "查看图表"}
        </Button> */}
        <Button
          type="primary"
          className="mx-4"
          size="large"
          onClick={handleClickAudit}
        >
          {"单位画像"}
        </Button>
        <Button
          type="primary"
          className="mx-4"
          size="large"
          onClick={handleClickMajor}
        >
          {"专业画像"}
        </Button>
        <Select
          size="large"
          value={companyName1}
          style={{ width: 200 }}
          onChange={handleChangeCompany1}
          options={companyList.map((item) => ({
            value: item,
            label: item
          }))}
        />
        <Button
          type="primary"
          className="mx-4"
          size="large"
          onClick={handleClickCompare}
        >
          {"画像对比"}
        </Button>
        <Upload {...uploadProps}>
          <Button type="primary" icon={<UploadOutlined />} size="large">
            文件上传
          </Button>
        </Upload>
      </header>

      <div className="flex-1 shirink-1 border-b border-gray-100">
        <Bubble.List
          ref={listRef}
          autoScroll
          roles={roles}
          style={{ padding: "20px", height: `${contentHeight - 40}px` }}
          items={messages.map(({ id, message, status }) => ({
            key: id,
            // loading: status === 'loading',
            role: status === "local" ? "local" : "ai",
            content: message
          }))}
        />
      </div>
      <footer ref={footerRef} className="p-6 shrink-0">
        {/* <Prompts className='mb-4' items={promptItems} wrap /> */}
        <Sender
          placeholder="请输入文字"
          loading={agent.isRequesting()}
          value={value}
          onChange={(v) => {
            setValue(v)
          }}
          // onSubmit={handleSubmit}
          onSubmit={(nextContent) => {
            onRequest(nextContent)
            extractContent(nextContent)

            setValue("")
          }}
          // onCancel={() => {
          //   setLoading(false);
          // }}
          autoSize={{ minRows: 3, maxRows: 6 }}
        />
      </footer>
    </div>
  )
}

export default Message
